package com.woniuxy.mini;

import com.woniuxy.core.service.ShopOrderService;
import com.woniuxy.entity.DTO.ShopOrderDTO;
import com.woniuxy.entity.ShopOrder;
import com.woniuxy.enums.ResponseEnum;
import com.woniuxy.enums.order.ShopOrderStatus;
import com.woniuxy.util.PageResult;
import com.woniuxy.util.ResponseData;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * 订单相关接口
 */
@Slf4j
@RestController
@RequestMapping("/shoporder")
public class ShopOrderController {

    @Autowired
    private ShopOrderService shopOrderService;

    /**
     * 创建订单
     */
    @PostMapping("/add")
    public ResponseData<ShopOrder> createShopOrder(@RequestBody ShopOrder shopOrder) {
        log.info("创建订单: {}", shopOrder);
        try {
            ShopOrder createdOrder = shopOrderService.createShopOrder(shopOrder);
            log.info("订单创建成功: {}", createdOrder.getOrderNumber());
            return ResponseData.ok(createdOrder);
        } catch (Exception e) {
            log.error("订单创建失败", e);
            return ResponseData.fail(ResponseEnum.ORDER_CREATE_FAILED);
        }
    }

    /**
     * 分页查询订单
     * 注意：@RequestBody 用于GET请求不太合适，建议改为@RequestParam
     */
    @GetMapping("/query")
    public ResponseData queryShopOrder(
            @RequestParam("pageNum") Integer pageNum,
            @RequestParam("pageSize") Integer pageSize,
            @RequestParam(name="userId", required = false) Integer userId,
            @RequestParam(name="status", required = false) Integer status) {

        log.info("分页查询订单: pageNum={}, pageSize={}, userId={}, status={}",
                pageNum, pageSize, userId, status);

        // 构建查询条件
        ShopOrder queryParam = new ShopOrder();
        queryParam.setUserId(userId);
        queryParam.setStatus(status);

        PageResult result = shopOrderService.queryShopOrder(pageNum, pageSize, queryParam);
        log.info("查询结果: 总记录数={}", result.getTotal());

        return ResponseData.ok(result);
    }

    /**
     * 获取订单详情
     */
    @GetMapping("/getOrderInfo/{orderId}")
    public ResponseData<ShopOrderDTO> getOrderInfo(@PathVariable("orderId") Integer orderId) {
        log.info("获取订单详情: orderId={}", orderId);

        ShopOrderDTO order = shopOrderService.getByOrderById(orderId);

        if (order == null) {
            log.warn("订单不存在: orderId={}", orderId);
            return ResponseData.fail(ResponseEnum.ORDER_NOT_FOUND);
        }

        return ResponseData.ok(order);
    }

    /**
     * 更新订单状态
     */
    @PostMapping("/status/{orderId}/{status}")
    public ResponseData updateOrderStatus(
            @PathVariable("orderId") Integer orderId,
            @PathVariable("status") Integer status) {

        log.info("更新订单状态: orderId={}, status={}", orderId, status);

        // 校验状态值是否合法
        if (!isValidStatus(status)) {
            log.warn("无效的订单状态: status={}", status);
            return ResponseData.fail(ResponseEnum.INVALID_ORDER_STATUS);
        }
        try {
            shopOrderService.updateOrderStatus(orderId, status);
            log.info("订单状态更新成功");
            return ResponseData.ok();
        } catch (Exception e) {
            log.error("订单状态更新失败", e);
            return ResponseData.fail(ResponseEnum.ORDER_UPDATE_FAILED);
        }
    }

    /**
     * 关闭订单
     */
    @PostMapping("/close/{orderNumber}") // 注意：参数类型应为String
    public ResponseData closeOrder(@PathVariable("orderNumber") String orderNumber) {
        log.info("关闭订单: orderNumber={}", orderNumber);
        try {
            shopOrderService.closeOrder(orderNumber);
            log.info("订单关闭成功");
            return ResponseData.ok();
        } catch (Exception e) {
            log.error("订单关闭失败", e);
            return ResponseData.fail(ResponseEnum.ORDER_CLOSE_FAILED);
        }
    }

    /**
     * 校验订单状态是否合法
     */
    private boolean isValidStatus(Integer status) {
        if (status == null) {
            return false;
        }
        for (ShopOrderStatus shopOrderStatus : ShopOrderStatus.values()) {
            if (shopOrderStatus.getCode() == status) {
                return true;
            }
        }
        return false;
    }
    //提交评价根据shopOrder表里的id
    @PostMapping("/comment/{orderId}/{commentInfo}")
    public ResponseData addComment(@PathVariable("orderId") Integer orderId,@PathVariable("commentInfo") String commentInfo) {
        try {
            shopOrderService.addComment(orderId,commentInfo);
            log.info("订单评价成功");
            return ResponseData.ok();
        }catch (Exception e){
            log.error("订单评价失败", e);
            return ResponseData.fail(ResponseEnum.ORDER_UPDATE_FAILED);
        }
    }
    //确认收货
    @PostMapping("/confirm/{orderId}")
    public ResponseData confirmOrder(@PathVariable("orderId") Integer orderId) {
        try {
            shopOrderService.confirmOrder(orderId);
            log.info("订单确认收货成功");
            return ResponseData.ok();
        }catch (Exception e){
            log.error("订单确认收货失败", e);
            return ResponseData.fail(ResponseEnum.ORDER_UPDATE_FAILED);
        }
    }
}